// pages/mine/myorder/myorder.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: ['全部', '购物车', '待付款', '已付款', '待收货'],
    currentTab: 0,
    orderList: [
      [], // 全部
      [], // 购物车
      [], // 待付款
      [], // 待发货
      []  // 待收货
    ],
    isAllChecked: false,
    // 添加状态映射
    statusMap: {
      '-1': '已取消',
      '0': '购物车',
      '1': '待支付',
      '2': '已支付',
      '3': '待收货',
      '4': '已完成'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 如果有传入tab参数，直接跳转到对应tab
    if (options.tab) {
      this.setData({
        currentTab: parseInt(options.tab)
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取用户ID
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取所有订单数据
    this.getAllOrders(userId);
    // 获取各种订单数据
    this.getOrdersByStatus(userId, 0); // 购物车
    this.getOrdersByStatus(userId, 1); // 待付款
    this.getOrdersByStatus(userId, 3); // 待收货
    this.getOrdersByStatus(userId, 2); // 待发货
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 从订单数组中提取所有商品项
   */
  extractOrderItems(orders) {
    let items = [];
    orders.forEach(order => {
      // 为每个商品添加订单ID，以便后续处理
      const orderItems = order.items.map(item => ({
        ...item,
        orderId: order.id,
        status: order.status,
        statusText: this.getStatusText(order.status),
        checked: false
      }));
      items = items.concat(orderItems);
    });
    return items;
  },

  getStatusText(status) {
    return this.data.statusMap[status] || '其他';
  },

  updateAllTab() {
    const { orderList } = this.data;
    let all = [];
    for (let i = 1; i < orderList.length; i++) {
      all = all.concat(orderList[i]);
    }
    console.log('更新全部标签页数据:', all);
    orderList[0] = all;
    this.setData({ orderList });
  },

  onTabChange(e) {
    const tabIndex = e.currentTarget.dataset.index;
    this.setData({
      currentTab: tabIndex
    }, () => {
      this.updateAllChecked();
    });
  },

  onNumChange(e) {
    const { type, index } = e.currentTarget.dataset;
    const { orderList, currentTab, tabList } = this.data;
    let list = JSON.parse(JSON.stringify(orderList));
    let item = list[currentTab][index];

    if (type === 'add') {
      item.num += 1;
    } else if (type === 'sub' && item.num > 1) {
      item.num -= 1;
    }

    // 如果是"全部"tab，需要同步到对应的原始tab
    if (currentTab === 0) {
      // 找到原始商品所在的tab和索引
      for (let i = 1; i < list.length; i++) {
        let idx = list[i].findIndex(x => x.id === item.id && (!x.orderId || x.orderId === item.orderId));
        if (idx !== -1) {
          list[i][idx].num = item.num;
          if (tabList[i] === '购物车') {
            wx.setStorageSync('cart', list[i]);
            // 刷新shops页面角标
            const pages = getCurrentPages();
            const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
            if (shopsPage && shopsPage.updateCartBadge) {
              shopsPage.updateCartBadge();
            }
          } else if (tabList[i] === '待付款') {
            this.updateOrderStorage('pendingOrders', item);
          }
          break;
        }
      }
    } else if (tabList[currentTab] === '购物车') {
      wx.setStorageSync('cart', list[currentTab]);
      // 刷新shops页面角标
      const pages = getCurrentPages();
      const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
      if (shopsPage && shopsPage.updateCartBadge) {
        shopsPage.updateCartBadge();
      }
    } else if (tabList[currentTab] === '待付款') {
      this.updateOrderStorage('pendingOrders', item);
    }

    this.setData({ orderList: list }, () => {
      this.updateAllTab();
    });
  },
  
  /**
   * 更新存储中的订单数据
   */
  updateOrderStorage(storageKey, updatedItem) {
    if (!updatedItem.orderId) return;
    
    let orders = wx.getStorageSync(storageKey) || [];
    const orderIndex = orders.findIndex(order => order.id === updatedItem.orderId);
    
    if (orderIndex !== -1) {
      const itemIndex = orders[orderIndex].items.findIndex(item => item.id === updatedItem.id);
      if (itemIndex !== -1) {
        orders[orderIndex].items[itemIndex].num = updatedItem.num;
        // 更新总金额
        const newTotal = orders[orderIndex].items.reduce((sum, item) => {
          return sum + (Number(item.price) * item.num);
        }, 0);
        orders[orderIndex].totalAmount = newTotal;
        wx.setStorageSync(storageKey, orders);
      }
    }
  },

  onCheckChange(e) {
    const { index } = e.currentTarget.dataset;
    const { orderList, currentTab } = this.data;
    let list = JSON.parse(JSON.stringify(orderList));
    let item = list[currentTab][index];
    
    item.checked = !item.checked;
    
    // 如果是"全部"tab，也要更新原始tab中的checked状态
    if (currentTab === 0) {
      for (let i = 1; i < list.length; i++) {
        let idx = list[i].findIndex(x => x.id === item.id && (!x.orderId || x.orderId === item.orderId));
        if (idx !== -1) {
          list[i][idx].checked = item.checked;
          if (i === 1) { // 购物车tab
            wx.setStorageSync('cart', list[i]);
            // 刷新shops页面角标
            const pages = getCurrentPages();
            const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
            if (shopsPage && shopsPage.updateCartBadge) {
              shopsPage.updateCartBadge();
            }
          }
          break;
        }
      }
    } else if (currentTab === 1) { // 购物车tab
      wx.setStorageSync('cart', list[currentTab]);
      // 刷新shops页面角标
      const pages = getCurrentPages();
      const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
      if (shopsPage && shopsPage.updateCartBadge) {
        shopsPage.updateCartBadge();
      }
    }

    this.setData({ orderList: list }, () => {
      this.updateAllChecked();
      this.updateAllTab();
    });
  },

  onAllCheck() {
    const { orderList, currentTab, isAllChecked, tabList } = this.data;
    let list = JSON.parse(JSON.stringify(orderList));
    const newCheck = !isAllChecked;

    list[currentTab].forEach(item => {
      item.checked = newCheck;
    });

    if (currentTab === 0) {
      // 全部tab：同步到各个原始tab
      for (let i = 1; i < list.length; i++) {
        list[i].forEach(originItem => {
          // 通过id和orderId匹配
          const match = list[0].find(
            allItem => allItem.id === originItem.id && (!allItem.orderId || allItem.orderId === originItem.orderId)
          );
          if (match) {
            originItem.checked = newCheck;
          }
        });
        // 同步到本地存储
        if (tabList[i] === '购物车') {
          wx.setStorageSync('cart', list[i]);
          // 刷新shops页面角标
          const pages = getCurrentPages();
          const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
          if (shopsPage && shopsPage.updateCartBadge) {
            shopsPage.updateCartBadge();
          }
        } else if (tabList[i] === '待付款') {
          // 批量更新pendingOrders的checked状态
          this.batchUpdateOrderStorage('pendingOrders', list[i]);
        } else if (tabList[i] === '待发货') {
          this.batchUpdateOrderStorage('shippingOrders', list[i]);
        } else if (tabList[i] === '待收货') {
          this.batchUpdateOrderStorage('receivingOrders', list[i]);
        }
      }
    } else if (currentTab === 1) {
      wx.setStorageSync('cart', list[currentTab]);
      // 刷新shops页面角标
      const pages = getCurrentPages();
      const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
      if (shopsPage && shopsPage.updateCartBadge) {
        shopsPage.updateCartBadge();
      }
    }

    this.setData({
      orderList: list,
      isAllChecked: newCheck
    }, () => {
      this.updateAllTab();
    });
  },

  // 批量更新订单存储的checked状态
  batchUpdateOrderStorage(storageKey, items) {
    let orders = wx.getStorageSync(storageKey) || [];
    items.forEach(item => {
      if (!item.orderId) return;
      const orderIndex = orders.findIndex(order => order.id === item.orderId);
      if (orderIndex !== -1) {
        const itemIndex = orders[orderIndex].items.findIndex(orderItem => orderItem.id === item.id);
        if (itemIndex !== -1) {
          orders[orderIndex].items[itemIndex].checked = item.checked;
        }
      }
    });
    wx.setStorageSync(storageKey, orders);
  },

  onBatchDelete() {
    const { orderList, currentTab, tabList } = this.data;
    const currentTabName = tabList[currentTab];
    let list = JSON.parse(JSON.stringify(orderList));
    const checkedItems = list[currentTab].filter(item => item.checked);
    
    if (checkedItems.length === 0) {
      wx.showToast({
        title: '请选择要删除的项目',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除选中的项目吗？',
      success: (res) => {
        if (res.confirm) {
          if (currentTab === 0) {
            // 全部tab，需要从各个原始tab删除
            this.deleteFromAllTabs(checkedItems);
          } else if (currentTabName === '购物车') {
            // 从购物车删除
            list[currentTab] = list[currentTab].filter(item => !item.checked);
            wx.setStorageSync('cart', list[currentTab]);
            // 刷新shops页面角标
            const pages = getCurrentPages();
            const shopsPage = pages.find(page => page.route === 'pages/shops/shops');
            if (shopsPage && shopsPage.updateCartBadge) {
              shopsPage.updateCartBadge();
            }
          } else if (currentTabName === '待付款') {
            // 从待付款删除
            this.deleteFromOrders('pendingOrders', checkedItems);
            list[currentTab] = list[currentTab].filter(item => !item.checked);
          } else if (currentTabName === '待发货') {
            // 从待发货删除
            this.deleteFromOrders('shippingOrders', checkedItems);
            list[currentTab] = list[currentTab].filter(item => !item.checked);
          } else if (currentTabName === '待收货') {
            // 从待收货删除
            this.deleteFromOrders('receivingOrders', checkedItems);
            list[currentTab] = list[currentTab].filter(item => !item.checked);
          }
          
          this.setData({ orderList: list }, () => {
            this.updateAllChecked();
            this.updateAllTab();
          });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },
  
  /**
   * 从全部标签页删除选中项目
   */
  deleteFromAllTabs(checkedItems) {
    // 从购物车删除
    let cart = wx.getStorageSync('cart') || [];
    const cartIds = checkedItems.filter(item => !item.orderId).map(item => item.id);
    if (cartIds.length > 0) {
      cart = cart.filter(item => !cartIds.includes(item.id));
      wx.setStorageSync('cart', cart);
    }
    
    // 从待付款删除
    const pendingIds = this.getOrderItemIds(checkedItems, 'pending');
    if (pendingIds.length > 0) {
      this.deleteFromOrders('pendingOrders', checkedItems.filter(item => item.status === 'pending'));
    }
    
    // 从待发货删除
    const shippingIds = this.getOrderItemIds(checkedItems, 'paid');
    if (shippingIds.length > 0) {
      this.deleteFromOrders('shippingOrders', checkedItems.filter(item => item.status === 'paid'));
    }
    
    // 从待收货删除
    const receivingIds = this.getOrderItemIds(checkedItems, 'shipped');
    if (receivingIds.length > 0) {
      this.deleteFromOrders('receivingOrders', checkedItems.filter(item => item.status === 'shipped'));
    }
    
    // 更新页面数据
    let orderList = this.data.orderList;
    orderList[1] = cart;
    this.setData({ orderList }, () => {
      this.onShow(); // 重新加载所有数据
    });
  },
  
  /**
   * 获取特定状态的订单项ID
   */
  getOrderItemIds(items, status) {
    return items
      .filter(item => item.status === status && item.orderId)
      .map(item => ({ id: item.id, orderId: item.orderId }));
  },
  
  /**
   * 从指定订单存储中删除项目
   */
  deleteFromOrders(storageKey, itemsToDelete) {
    let orders = wx.getStorageSync(storageKey) || [];
    let modified = false;
    
    // 按订单ID分组
    const itemsByOrderId = {};
    itemsToDelete.forEach(item => {
      if (item.orderId) {
        if (!itemsByOrderId[item.orderId]) {
          itemsByOrderId[item.orderId] = [];
        }
        itemsByOrderId[item.orderId].push(item.id);
      }
    });
    
    // 处理每个订单
    for (const orderId in itemsByOrderId) {
      const orderIndex = orders.findIndex(order => order.id === orderId);
      if (orderIndex !== -1) {
        const itemIds = itemsByOrderId[orderId];
        // 如果删除的是订单中的所有商品，则删除整个订单
        if (orders[orderIndex].items.length === itemIds.length) {
          orders.splice(orderIndex, 1);
        } else {
          // 否则只删除选中的商品
          orders[orderIndex].items = orders[orderIndex].items.filter(
            item => !itemIds.includes(item.id)
          );
          // 更新订单总金额
          const newTotal = orders[orderIndex].items.reduce((sum, item) => {
            return sum + (Number(item.price) * item.num);
          }, 0);
          orders[orderIndex].totalAmount = newTotal;
        }
        modified = true;
      }
    }
    
    if (modified) {
      wx.setStorageSync(storageKey, orders);
    }
  },

  onBatchPay() {
    const { orderList, currentTab, tabList } = this.data;
    const currentTabName = tabList[currentTab];
    const checkedItems = orderList[currentTab].filter(item => item.checked);
    
    if (checkedItems.length === 0) {
      wx.showToast({ title: '请选择要结算的订单', icon: 'none' });
      return;
    }
    
    if (currentTabName === '购物车') {
      // 购物车结算
      wx.setStorageSync('tempOrder', checkedItems);
      wx.navigateTo({
        url: '/pages/order/payment'
      });
    } else if (currentTabName === '待付款') {
      // 待付款订单结算
      // 按订单ID分组
      const orderIds = [...new Set(checkedItems.map(item => item.orderId))];
      if (orderIds.length > 1) {
        wx.showToast({
          title: '一次只能支付一个订单',
          icon: 'none'
        });
        return;
      }
      
      // 获取完整订单信息
      const pendingOrders = wx.getStorageSync('pendingOrders') || [];
      const orderInfo = pendingOrders.find(order => order.id === orderIds[0]);
      
      if (orderInfo) {
        wx.showModal({
          title: '确认支付',
          content: `订单总额: ¥${(orderInfo.totalAmount + orderInfo.deliveryFee).toFixed(2)}`,
          cancelText: '取消',
          confirmText: '支付',
          success: (res) => {
            if (res.confirm) {
              // 用户确认支付
              this.payPendingOrder(orderInfo);
            }
          }
        });
      }
    } else {
      let total = checkedItems.reduce((sum, item) => {
        return sum + (Number(item.price) * item.num);
      }, 0);
      
      wx.showToast({
        title: `总金额: ¥${total.toFixed(2)}`,
        icon: 'none'
      });
    }
  },
  
  /**
   * 支付待付款订单
   */
  payPendingOrder(orderInfo) {
    // 从待付款列表中移除
    let pendingOrders = wx.getStorageSync('pendingOrders') || [];
    pendingOrders = pendingOrders.filter(order => order.id !== orderInfo.id);
    wx.setStorageSync('pendingOrders', pendingOrders);
    
    // 更新订单状态为已支付
    orderInfo.status = 'paid';
    
    // 添加到待发货列表
    let shippingOrders = wx.getStorageSync('shippingOrders') || [];
    shippingOrders.push(orderInfo);
    wx.setStorageSync('shippingOrders', shippingOrders);
    
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          // 刷新页面数据
          this.setData({ currentTab: 3 }, () => {
            this.onShow();
          });
        }, 2000);
      }
    });
  },

  updateAllChecked() {
    const { orderList, currentTab } = this.data;
    const list = orderList[currentTab];
    const allChecked = list.length > 0 && list.every(item => item.checked);
    this.setData({ isAllChecked: allChecked });
  },

  // 获取用户所有订单
  getAllOrders(userId) {
    wx.request({
      url: `http://localhost:8080/orders/by-user`,
      method: 'GET',
      data: {
        userId: userId
      },
      success: (res) => {
        console.log('获取所有订单响应:', res.data);
        if (res.data.success) {
          const orders = res.data.data;
          // 获取每个订单的订单项
          this.getOrderItemsForOrders(orders, (processedOrders) => {
            let orderList = this.data.orderList;
            orderList[0] = processedOrders;
            this.setData({ orderList }, () => {
              this.updateAllChecked();
            });
          });
        } else {
          wx.showToast({
            title: '获取订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取所有订单失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 获取订单项
  getOrderItems(orderId, callback) {
    wx.request({
      url: `http://localhost:8080/orderitems`,
      method: 'GET',
      data: {
        orderId: orderId
      },
      success: (res) => {
        console.log(`订单${orderId}的详情:`, res.data);
        if (res.data.success) {
          const orderItems = res.data.data;
          // 获取每个订单项的商品信息并回调
          this.getProductsForOrderItems(orderItems, (itemsWithProducts) => {
            callback(itemsWithProducts);
          });
        } else {
          console.error(`获取订单${orderId}详情失败:`, res.data.message);
          callback([]);
        }
      },
      fail: (err) => {
        console.error(`获取订单${orderId}详情失败:`, err);
        callback([]);
      }
    });
  },

  // 获取订单项的商品信息
  getProductsForOrderItems(orderItems, callback) {
    if (!orderItems || orderItems.length === 0) {
      callback([]);
      return;
    }

    let itemsWithProducts = [];
    let completedCount = 0;
    const totalItems = orderItems.length;

    orderItems.forEach(item => {
      this.getProductInfo(item.productId, (product) => {
        // 将商品信息添加到订单项中
        const itemWithProduct = {
          ...item,
          product: product // 将获取到的商品详情作为 product 属性添加到 item 中
        };
        itemsWithProducts.push(itemWithProduct);
        completedCount++;
        if (completedCount === totalItems) {
          callback(itemsWithProducts); // 在所有商品信息都获取完毕后调用 callback
        }
      });
    });
  },

  // 获取商品信息
  getProductInfo(productId, callback) {
    wx.request({
      url: `http://localhost:8080/products/${productId}`,
      method: 'GET',
      success: (res) => {
        console.log(`商品${productId}信息:`, res.data);
        if (res.data.success) {
          callback(res.data.data);
        } else {
          console.error(`获取商品${productId}信息失败:`, res.data.message);
          callback(null);
        }
      },
      fail: (err) => {
        console.error(`获取商品${productId}信息失败:`, err);
        callback(null);
      }
    });
  },

  // 获取订单项并填充商品信息
  getOrderItemsForOrders(orders, callback) {
    if (!orders || orders.length === 0) {
      callback([]);
      return;
    }

    let processedOrders = [];
    let completedCount = 0;
    const totalOrders = orders.length;

    orders.forEach(order => {
      // 获取订单详情，并在回调中获取商品信息并处理
      // getOrderItems 内部会调用 getProductsForOrderItems
      this.getOrderItems(order.id, (orderItemsWithProducts) => {
        // orderItemsWithProducts 现在应该包含了附加了 product 信息的订单项
        // 将订单项数据转换为页面需要的格式
        const formattedItems = orderItemsWithProducts.map(item => ({
          id: item.id,
          orderId: order.id,
          postalCode: order.postalCode || '',
          status: order.status.toString(),
          statusText: this.data.statusMap[order.status.toString()],
          checked: false,
          // 现在可以安全地从 item.product 获取商品信息了
          img: item.product?.coverImg || '',
          title: item.product?.title || '',
          desc: item.product?.description || '',
          price: item.product?.price || 0,
          num: item.productCount, // num 对应后端 productCount
          total: item.total,
          productId: item.productId,
          // 添加订单总金额
          orderTotal: order.totalPrice || 0,
          // 添加商品简介
          brief: item.product?.introduce || '暂无简介'
        }));

        processedOrders.push(...formattedItems);
        completedCount++;
        if (completedCount === totalOrders) {
          callback(processedOrders); // 在所有订单的订单项都处理完毕后调用 callback
        }
      });
    });
  },

  // 跳转到商品详情页
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id;
    console.log('点击了商品，ID:', productId);
    // TODO: 跳转到商品详情页
    // 这里假设商品详情页路径为 '/pages/productDetail/productDetail'，并接受一个 id 参数
    wx.navigateTo({
      url: '/pages/shops/shopsdetails/shopsdetail?id=' + productId
    });
  },

  // 跳转到订单详情页
  onOrderTap(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/detail/detail?id=${orderId}`
    });
  },

  // 获取订单数据的方法
  getOrdersByStatus(userId, status) {
    wx.request({
      url: `http://localhost:8080/orders/${userId}/${status}`,
      method: 'GET',
      success: (res) => {
        console.log(`获取状态${status}订单响应:`, res.data);
        if (res.data.success) {
          const orders = res.data.data;
          // 调用 getOrderItemsForOrders 来获取订单项并填充商品信息
          this.getOrderItemsForOrders(orders, (processedOrders) => {
            let orderList = this.data.orderList;
            switch(status) {
              case 0: // 购物车
                orderList[1] = processedOrders;
                break;
              case 1: // 待付款
                orderList[2] = processedOrders;
                break;
              case 2: // 待发货
                orderList[3] = processedOrders;
                break;
              case 3: // 待收货
                orderList[4] = processedOrders;
                break;
            }
            this.setData({ orderList }, () => {
              this.updateAllTab();
              this.updateAllChecked();
            });
          });
        } else {
          wx.showToast({
            title: '获取订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error(`获取状态${status}订单失败:`, err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 更新全部标签页
  updateAllTab() {
    const { orderList } = this.data;
    let all = [];
    for (let i = 1; i < orderList.length; i++) {
      all = all.concat(orderList[i]);
    }
    console.log('更新全部标签页数据:', all);
    orderList[0] = all;
    this.setData({ orderList });
  },
})